﻿		/* Get the number of moves. */
		function getMoves()
		{
		   if ( wave.getState() )
		   {
			  return parseInt( wave.getState().get( "moves", "0" ) );
		   }
		   else
		   {
			  return 0;
		   }
		}
		
		
		
		/* 1 React to a cell click. */
		function cellClick( row, col )
		{
		 if(IsRightTime(1,7)){ // added to lock availablity of form
		   
		   // Get the current state of play.
		   var game = gameState();
		   var name=wave.getViewer().getDisplayName();
		   var num=0;
		   var par_id=wave.getViewer().getId();
		   var new_account=accountState();
		   // Make the move.
			  if (col<3)   {
				game[row][col] = !game[row][col];
				if (game[row][col])
					new_account[row][col]=wave.getViewer().getId();
				else
					new_account[row][col]="";
			 }

		   // Write the state of play back to the Wave.
		   wave.getState().submitDelta( { "game"  : wave.util.printJson( game ),
										  "moves" : getMoves() + 1,
										  "account":wave.util.printJson(new_account)});
		  }
		}

		/* The ial state of a game. */          
		function defaultGame()
		{
		   return new Array(
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false),
			  new Array( false, false, false));
		}
		function defaultAccount()
		{
		   return new Array(
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""),
			  new Array( "", "", ""));
		}

		
		/*Additional function*/
		function isDone(game){
		var sub_count = 0;
			var row_count = 0;
			for ( row = 0; row < 16; row++ )
			{   sub_count = 0;
				for ( col = 0; col < 3; col++ ){
					if ( game[ row ][ col ] ) 
						sub_count=sub_count+1;
				}
				if (sub_count>0)
					row_count=row_count+1;
					
			}
			row_count=16-row_count;
			return row_count;

		}


		/* Get the state for the current game. */
		function gameState()
		{
		   if ( wave.getState() )
		   {
			  var game = eval( "(" + wave.getState().get( "game", defaultGame() ) + ")" );
			  
			  return game ? game : defaultGame();
		   }
		   else
		   {
			  return defaultGame();
		   }
		}
		
		/* Get the state for the last week game. */
		function last_week_gameState()
		{
		   if ( wave.getState() )
		   {
			  var last_week_game = eval( "(" + wave.getState().get( "last_week_game", defaultGame() ) + ")" );
			  
			  return last_week_game ? last_week_game : defaultGame();
		   }
		   else
		   {
			  return defaultGame();
		   }
		}
		
		
		
		
		/* Get the account for the current game. */
		function accountState()
		{
		   if ( wave.getState() )
		   {
			  var account = eval( "(" + wave.getState().get( "account" ) + ")" );
			  
			  return account ? account : defaultAccount();
		   }
		   else
		   {
			  return defaultAccount();
		   }
		}

		/* Get the current games column from the state */
		function GamesStrState(){
			if ( wave.getState() ){
				var GamesStr = wave.getState().get( "GamesStr" );
				return GamesStr ? GamesStr : "";
		   }
		   else{
		   return "";
		   }
		}
		
		/* Get the current results column from the state as an array*/
		/* (type==0) -> games results , (type==1) -> first prizes */
		/*	if results are not present return []*/
		function Results(type){ 
			if ( wave.getState() ){
			  var ResultsStr = wave.getState().get( "ResultsStr" );
				if(!ResultsStr){
					return [];
				}
				else{
					var TypesArray = ResultsStr.split("#");
					var ResultsArray = TypesArray[type].split("$");
					return ResultsArray;
				}
		   }
		   else
		   {
			  return [];
		   }
		}
		
		/* 	Get the recommendations from the state as an array*/
		/*	(type==0) -> textual recommendations, (type==1) -> final recommendations */
		function Recommendations(type){
			if ( wave.getState() ){
				var RecStr = wave.getState().get( "RecStr" );
				if(!RecStr){
					return [];
				}
				else{
					var TypesArray = RecStr.split("#");
					var RecArray = TypesArray[type].split("$");
					return RecArray;
				}
		   }
		   else
		   {
			  return [];
		   }
		}
		
		/* Set the state of a cell in the display. */
		function setCell( row, col, on )
		{
		   document.getElementById( "cell" + row + col ).className = on ? "cellOn" : "cellOff";
		}

		/* Do Something for each cell in the game. */
		function forEachCell( f )
		{
		   for ( row = 0; row < 16; row++ )
		   {
			  for ( col = 0; col < 3; col++ )
			  {
				 f( row, col );
			  }
		   }
		}

		/* Refresh the grid based on the current game state. */
		function refreshGrid( gameState )
		{
		   forEachCell( function( row, col ) { setCell( row, col, gameState[ row ][ col ] ) } );
		}

		/* Get the count of cells switched on. */
		function onCount( gameState )
		{
		   var count = 0;

		   forEachCell( function( row, col ) { if ( gameState[ row ][ col ] ) count++; } );
		   
		   return count;
		}


		function fillingAccount(Participants,account){
			var howManyTotla_t="";
			for ( par = 0; par < Participants.length; par++ ){
				var name=Participants[par].getDisplayName();
				var id=Participants[par].getId();	
				var count=0;
				forEachCell(function(row,col){if (account[row][col]==id) count++;});
				var square_t=count==1?" square":" squares";
				var howMany_t=name+" filled "+count+square_t;
				var howManyTotla_t=howManyTotla_t+"\n"+howMany_t+". ";
			}
			return howManyTotla_t;
		}
		 
		 
		/* Update the display of number of moves. */
		function refreshMoves( gameState )
		{
		   var moves   = getMoves();
		   var moves_t = moves == 1 ? "move" : "moves";
		   var counter= isDone(gameState);
		   var counter_t= counter==1?" game ":" games ";
		   
		   document.getElementById( "moves" ).innerHTML =
			  "After " + moves + " " + moves_t + " You still have "+ counter+counter_t+ "left to fill.";
			document.getElementById( "Who" ).innerHTML = fillingAccount(wave.getParticipants(),accountState());
		   
		}

		/* After the state has changed, refresh the display. */
		function stateUpdated()
		{
		   var game = gameState();		   
		   refreshGrid( game );
		   refreshMoves( game );
		   RefreshGames();
		   RefreshRec();
		   gadgets.window.adjustHeight();
		}

		/* Reset the state of the game. */
		function resetGame()
		{	
			answer = confirm("Do you really want to Reset");
			if (answer !=0){ 
				var par=wave.getParticipants();
				for ( i = 0; i < par.length; i++ ){
					var id =par[i].getId();
					wave.getState().submitDelta( {id:"0"});
				}
				
				wave.getState().submitDelta( { 	"game"  : wave.util.printJson(defaultGame()),
												"moves" : "0" ,
												"account":wave.util.printJson(defaultAccount()),
												} );
			}
		}

		/* Show some help. */
		function showHelp()
		{
		   alert(  "כל שבוע מתפרסמת רשימה של 16 משחקי כדורגל הנערכים בסוף השבוע"+ " " +
		"והמשתתפים בטופס הטוטו בשבוע הזה. המשתתף צריך לנחש את תוצאת 16 המשחקים"+
		".");
		}
				  
		/* Initialise the display. */
		function init()
		{
		
			if ( wave && wave.isInWaveContainer() )
			{
			  wave.setStateCallback( stateUpdated );
			}
			
			_IG_AdjustIFrameHeight();								   			
			RefreshData(0);//get the current games
			RefreshData(1);//get the results
			RefreshData(2);//get the recommendations
			RefreshData(3);//get the current time
			/* Set the page displayed according to the current play mode */
			setTimeout("getPage()",200);
			gadgets.window.adjustHeight();
		}
		

		gadgets.util.registerOnLoadHandler( init );
		function defaultResults(){
			return new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
		}
		function checkResults (){
			var gamesResults=Results(0);
			var gamesMoney=Results(1);
			var game = gameState();
			var account=accountState();
			var last_week_results=defaultResults();
			var fault=new Array();
			var par=wave.getParticipants();
			var counter=0;
			var last_week_money=0;
			fault.length=par.length;
			for ( i = 0; i < fault.length; i++ )
				fault[i]=0;
				
			for ( row = 0; row < 16; row++ ){
				if (gamesResults[row]==1)
					var winningSquare=2;
				
				if (gamesResults[row]=='x')
					var winningSquare=1;
				
				if (gamesResults[row]==2)
					var winningSquare=0;
				
				if (game[row][winningSquare]){  //need to change -> what is result[x]?
					counter=counter+1;
					last_week_results[row]=1;
					for ( i = 0; i < par.length; i++ ){
						for ( col = 0; col < 3; col++ ){
							if (par[i].getId()==account[row][col]){
								fault[i]--;	
								break;	
							}
						}	
					}	
				}
				else{
					for ( i = 0; i < par.length; i++ ){
						for ( col = 0; col < 3; col++ ){
							if (par[i].getId()==account[row][col]){
								fault[i]++;	
								break;	
							}
						}	
					}
				}
			}
			
			var idiot=whoseFault(par,fault);
			
			if (counter>12)
				last_week_money=gamesMoney[17-counter];
			//Saving the old form.
			lastWeek(last_week_money,idiot,last_week_results);
			
			var counter_s = counter == 1 ? "game" : "games";
			//Would be displayed as in last week's results. The idiot's picture would be displayed.
			alert("You have won in "+counter+" "+ counter_s);
			alert("It's "+idiot+ "'s fault you didn't win them all!");
			alert("You've Won "+last_week_money+" shekels");
		}
		
		function whoseFault(par,fault){
			var max_fault=0;
			var idiot_i=-1;
			for ( i = 0; i < par.length; i++ ){
				if (fault[i]>max_fault){
					max_fault=fault[i];
					idiot_i=i;
				}
			}
			var idiot=idiot_i==-1? "nobody": par[idiot_i].getDisplayName();
			return idiot;
		}
		
		function getFault(id)
		{
		   if ( wave.getState() )
		   {
			  return parseInt( wave.getState().get( id, "0" ) );
		   }
		   else
		   {
			  return 0;
		   }
		}
		
		function compute_price(){
		var price=1000;
		document.getElementById('cost_number').innerHTML = price;
		}
		
		function lastWeek(last_week_money,idiot,last_week_results){
			var str=GamesStrState();
			 var game = gameState();
			wave.getState().submitDelta({ 	"last_week_game"  : wave.util.printJson( game ), //last week's filled form
											"last_week_GamesStr" : str, //the names of last week's games
											"last_week_money"  : last_week_money, //how much money did the gruop win 
											"idiot" : idiot, //the id of last week's idiot
											"last_week_results":wave.util.printJson(last_week_results)}); //an array of 0s and 1s: 1 for a correct guess 0 for a wronge one. 
		}
		
		/* enter the start day and end day and the function returns "true" if the current time is between start and end*/
		function IsRightTime(start,end){
			var Time = wave.getState().get("TimeStr");
			if(Time){
				Time = Time.split("#");
				Time = parseInt(Time[0]);
			}
			else{
				Time = new Date();
				Time = Time.getDay()+1;
			}
			if(Time >= start && Time <= end){
				return true;
			}
			else{
				return false;
			}
		}
		
		
		//watch the state for debuging
		function debug(){ 
			var s = wave.getState().toString();
			alert(s);
		}
	
	
	

	/********** appengine part ****************************/

		 
		
		// a special request bybasing cache
		function makeCachedRequest(url, response, params, refreshInterval) {
			var ts = new Date().getTime();
			var sep = "?";
			if (refreshInterval && refreshInterval > 0) {
				ts = Math.floor(ts / (refreshInterval * 1000));
			}
			if (url.indexOf("?") > -1) {
				sep = "&";
			}
			url = [ url, sep, "nocache=", ts ].join("");
			gadgets.io.makeRequest(url, response, params);
		}
		
		
		
		/* 	getting data into the state: 	
			(type==0)-> games			 
			(type==1)-> results			
			(type==2)-> recommendations	 
			(type==3)-> returns the time and date string */
			
			
		function RefreshData(type){
			var str;
			var	time;		
			function response(obj) {  
				//obj.text contains the text of the page that was requested  
				str = obj.text;
				if(type==0){
					wave.getState().submitDelta({ "GamesStr" : str});
				}
				if(type==1){
					wave.getState().submitDelta({ "ResultsStr" : str});
				}
				if(type==2){
					wave.getState().submitDelta({ "RecStr" : str});
				}
				if(type==3){
					wave.getState().submitDelta({ "TimeStr" : str});
				}
			}
			
			var params = {};  
			params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
			var url;
			if(type==0){
				url = "http://gilivaturitest.appspot.com/gadgetRequestServlet"; 
			}
			if(type==1){
				url = "http://gilivaturitest.appspot.com/gadgetRequestResultsServlet";
			}
			if(type==2){
				url = "http://gilivaturitest.appspot.com/gadgetRequestRecServlet";
			}
			if(type==3){
				url = "http://gilivaturitest.appspot.com/gadgetRequestTimeServlet";
			}
			makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh
		}
		
		
				
		function RefreshGames(){
			var GamesStr = GamesStrState();
			var games_arr;
			if(GamesStr && GamesStr!=""){
				var FieldsArray = GamesStr.split("#");
				for(j=3;j<7;j++){
					tempFieldArray = FieldsArray[3-(j-3)].split("$");
					for (i=0;i<16;i++){
						document.getElementById( "cell" + i + j ).innerHTML = tempFieldArray[15-i];
					}
				}
			}
		}
		
		function RefreshRec(){
			if(IsRightTime(1,7)){ //fill updated recomendations
				TextRecArr = Recommendations(1);
				FinalRecArr = Recommendations(0);
				if(TextRecArr && FinalRecArr){
					var TempCell;
					for(i=0;i<16;i++){
						TempCell = document.getElementById( "cell" + i + '6');
						TempCell.title = TextRecArr[15-i] + " " + FinalRecArr[15-i];
					}
				}
			}
			else{//clear the recommendations
				for(i=0;i<16;i++){
						TempCell = document.getElementById( "cell" + i + '6');
						TempCell.title = "";
					}
			}
		}
    /*********	appengine part end 	************************/
    
    /********** Design Part ********************************/
    function openPage(id){
  		document.getElementById('homePage').style.display = 'none';
  		document.getElementById(id).style.display = 'block';
  		/* ADdded in order for wave to save current page being viewed - OREN*/
  		wave.getState().submitDelta( {page:"1"});
  	}
  	function backToMain(id){
  		document.getElementById(id).style.display = 'none';
  		document.getElementById('homePage').style.display = 'block';		
  	}
  	function openInfo(id){
  		document.getElementById('homePage').style.display = 'none';
  		document.getElementById(id).style.display = 'block';
  	}
  	function openTurn(){
  		document.getElementById('turn_closed').style.display = 'none';
  		document.getElementById('turn_opened').style.display = 'block';
  	}
  	function closeTurn(){
  		document.getElementById('turn_closed').style.display = 'block';
  		document.getElementById('turn_opened').style.display = 'none';
  	}
  	function openCost(){
  		document.getElementById('cost_closed').style.display = 'none';
  		document.getElementById('cost_opened').style.display = 'block';
  	}
  	function closeCost(){
  		document.getElementById('cost_closed').style.display = 'block';
  		document.getElementById('cost_opened').style.display = 'none';
  	}
  	function openBtn(el){
  		var id = el.id;
  		document.getElementById('turn_closed').style.display = 'none';
  		document.getElementById('turn_opened').style.display = 'block';
  	}
  	function newGameMouseOver() {
  	  document.getElementById('new_game_left').style.backgroundPosition = "left -30px";
  	  document.getElementById('new_game_right').style.backgroundPosition = "right -30px";
  	}
  	function newGameMouseOut() {
  	  document.getElementById('new_game_left').style.backgroundPosition = "left 0px";
  	  document.getElementById('new_game_right').style.backgroundPosition = "right 0px";
  	}
  	function lastWeekMouseOver() {
  	  document.getElementById('last_week_left').style.backgroundPosition = "left -30px";
  	  document.getElementById('last_week_right').style.backgroundPosition = "right -30px";
  	}
  	function lastWeekMouseOut() {
  	  document.getElementById('last_week_left').style.backgroundPosition = "left 0px";
  	  document.getElementById('last_week_right').style.backgroundPosition = "right 0px";
  	}
    /********* Design Part End *******************************/
    
    /******** NEW FUNTIONS **********************************/
    
    /* This function was added by OREN */
    /* The function changes the page that is being displayed according to the key "page"
    if page==1 then family mode is on
    if page==2 head2head mode is on
    if page is not defined, no mode was selected yet ******************************/
    
    function getPage() {
      var display;
      /*This line should get 1 after someone clicked the "family page" link*/
      display=parseInt(wave.getState().get("page"));
      
      if (display==1) {

        /* Show family page, hide homepage*/
			  document.getElementById('homePage').style.display = 'none';
  		  document.getElementById('familyPage').style.display = 'block';        
      }      
    }
    